package core

import (
	"base-web/global"
	"base-web/initalize"
	"context"
	"fmt"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

//启动项目
func RunServer() {
	addr := global.BASE_CONFIG.System.Addr
	g := initalize.Routers()
	//g.Run(":" + addr)
	server := &http.Server{
		Addr:           ":" + addr,
		Handler:        g,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	go server.ListenAndServe()
	serverClose(server)
}

//优雅关闭
func serverClose(server *http.Server) {
	ch := make(chan os.Signal)
	// SIGQUIT:用户发送QUIT字符(Ctrl+/)触发  SIGINT:用户发送INTR字符(Ctrl+C)触发 SIGHUP:终端控制进程结束(终端连接断开)
	signal.Notify(ch, syscall.SIGEMT, syscall.SIGQUIT, syscall.SIGINT, syscall.SIGHUP)
	sig := <-ch
	fmt.Println("获得一个信号：", sig)
	cxt, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	err := server.Shutdown(cxt)
	if err != nil {
		fmt.Println("err", err)
	}

	// 看看实际退出所耗费的时间
	fmt.Println("------退出--------")
}
